<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="88px">
            <el-form-item label="申请单号" prop="applicationNo">
                <el-input v-model="queryParams.applicationNo" placeholder="请输入申请单号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="申请人" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入申请人姓名" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="申请状态" prop="applicationStatus">
                <el-select v-model="queryParams.applicationStatus" placeholder="请选择状态" clearable>
                    <el-option v-for="item in applicationStatusOptions" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- <el-row :gutter="10" class="mb8">
       <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dashboard:withdrawalApplication:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

        <el-table v-loading="loading" :data="withdrawalApplicationList">
            <el-table-column label="申请单号" align="center" prop="applicationNo" width="200" />
            <el-table-column label="订单号" align="center" prop="orderNo" width="200">
                <template slot-scope="scope">
                    {{ scope.row.orderNo || 'PS订单' }}
                </template>
            </el-table-column>
            <el-table-column label="申请人" align="center" prop="userName" />
            <el-table-column label="提现类型" align="center" prop="withdrawalType">
                <template slot-scope="scope">
                    <span>{{(withdrawalTypeOptions.find(d => d.dictValue === scope.row.withdrawalType) || {}).dictLabel
                        || scope.row.withdrawalType}}</span>
                </template>
            </el-table-column>
            <el-table-column label="申请金额" align="center" prop="applicationAmount" />
            <el-table-column label="申请状态" align="center" prop="applicationStatus">
                <template slot-scope="scope">
                    <span>{{(applicationStatusOptions.find(d => d.dictValue === scope.row.applicationStatus) ||
                        {}).dictLabel || scope.row.applicationStatus}}</span>
                </template>
            </el-table-column>
            <el-table-column label="当前审批人" align="center" prop="currentApproverName" />
            <el-table-column label="申请时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-s-check" @click="handleApprove(scope.row)"
                        v-if="scope.row.currentApproverId == userId && scope.row.applicationStatus < 3"
                        v-hasPermi="['dashboard:withdrawalApplication:edit']">审批</el-button>
                    <el-button size="mini" type="text" icon="el-icon-view" @click="handleApprove(scope.row)"
                        v-else>查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-money" @click="handlePay(scope.row)"
                        v-if="scope.row.applicationStatus === 3"
                        v-hasPermi="['dashboard:withdrawalApplication:pay']">打款</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 审批提现申请对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" label-width="120px">
                <el-row>
                    <el-col :span="24" v-if="receiptImageList.length > 0">
                        <el-form-item label="收款图片：">
                            <div class="receipt-images-container">
                                <el-image v-for="(url, index) in receiptImageList" :key="index"
                                    class="receipt-image" :src="url"
                                    :preview-src-list="receiptImageList"
                                    fit="cover">
                                </el-image>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="申请人：">{{ form.userName }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="支付宝账号：">{{ form.alipayAccount }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单号：">{{ form.orderNo }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="任务类型：">{{ form.orderTaskTypeName }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="提现类型：">
                            <span>{{(withdrawalTypeOptions.find(d => d.dictValue === form.withdrawalType) ||
                                {}).dictLabel ||
                                form.withdrawalType}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="申请金额：">￥{{ form.applicationAmount }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="用户申请备注：">{{ form.remark }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="售后收款备注：">
                            <div class="payment-remark-container">
                                {{ form.afterSalePaymentRemark || '暂无备注' }}
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-divider></el-divider>
                <el-form-item label="审批历史">
                    <el-timeline>
                        <el-timeline-item v-for="(history, index) in approveHistoryList" :key="index"
                            :timestamp="history.timestamp" :color="history.action === '通过' ? '#67C23A' : '#F56C6C'">
                            <p>审批人: {{ history.approverName }}</p>
                            <p>审批动作: {{ history.action }}</p>
                            <p>审批意见: {{ history.remark }}</p>
                            <p v-if="history.approveImageUrl">
                                凭证图片: 
                                <div class="approval-images-container">
                                    <el-image 
                                        v-for="(imageUrl, imgIndex) in getApprovalImageList(history.approveImageUrl)" 
                                        :key="imgIndex"
                                        class="approval-image" 
                                        :src="imageUrl"
                                        :preview-src-list="getApprovalImageList(history.approveImageUrl)"
                                        fit="cover">
                                    </el-image>
                                </div>
                            </p>
                        </el-timeline-item>
                    </el-timeline>
                </el-form-item>
                <div v-if="canApprove">
                    <el-divider></el-divider>
                    <el-form-item label="审批意见" prop="approveRemark">
                        <el-input v-model="approveForm.remark" type="textarea" placeholder="请输入审批意见" />
                    </el-form-item>
                    <el-form-item label="凭证图片">
                        <el-upload class="upload-demo" ref="upload" action="#" :http-request="handleFileUpload"
                            :on-success="handleFileSuccess" :on-remove="handleFileRemove" :file-list="fileList"
                            :limit="3" accept=".jpg,.jpeg,.png" list-type="picture-card"
                            :on-preview="handleApprovalPicturePreview" :on-exceed="handleApprovalPictureExceed">
                            <i class="el-icon-plus"></i>
                            <div slot="tip" class="el-upload__tip">最多上传3张jpg/png文件，每张不超过2MB</div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="下一审批人" prop="nextApproverId" v-if="showNextApproverSelect">
                        <el-select v-model="approveForm.nextApproverId" placeholder="请选择下一审批人" clearable>
                            <el-option v-for="item in nextApproverOptions" :key="item.userId"
                                :label="item.nickName + ' (' + item.userName + ')'" :value="item.userId" />
                        </el-select>
                    </el-form-item>
                </div>

            </el-form>
            <div slot="footer" class="dialog-footer" v-if="canApprove">
                <el-button type="success" @click="submitApprove('APPROVE')">通 过</el-button>
                <el-button type="danger" @click="submitApprove('REJECT')">驳 回</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listWithdrawalApplication, getWithdrawalApplication, approveApplication, getApprovers, transferToAlipay } from "@/api/dashboard/withdrawalApplication";
import { uploadFile } from "@/api/system/file"; // Import uploadFile

export default {
    name: "WithdrawalApplication",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 提现申请表格数据
            withdrawalApplicationList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 当前是否可以审批
            canApprove: false,
            // 提现类型字典
            withdrawalTypeOptions: [
                { dictLabel: "首款", dictValue: 1 },
                { dictLabel: "尾款", dictValue: 2 }
            ],
            // 申请状态字典
            applicationStatusOptions: [
                { dictLabel: "待审批", dictValue: 0, nextRole: '财务' },
                { dictLabel: "一级审批通过", dictValue: 1, nextRole: 'admin' },
                { dictLabel: "二级审批通过", dictValue: 2, nextRole: null },
                { dictLabel: "最终审批通过", dictValue: 3 },
                { dictLabel: "已驳回", dictValue: 4 },
                { dictLabel: "已打款", dictValue: 5 },
                { dictLabel: "用户已取消", dictValue: 6 },
                { dictLabel: "打款中", dictValue: 7 }
            ],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                applicationNo: null,
                userName: null,
                applicationStatus: null,
            },
            // 表单参数
            form: {},
            // 审批表单
            approveForm: {
                action: null,
                remark: null,
                nextApproverId: null,
                approveImageUrl: null // 新增字段，用于存储凭证图片URL
            },
            // 审批历史
            approveHistoryList: [],
            // 下一审批人选项
            nextApproverOptions: [],
            // 已上传文件列表，用于 el-upload 组件
            fileList: []
        };
    },
    computed: {
        userId() {
            return this.$store.state.user.id;
        },
        showNextApproverSelect() {
            if (this.form.applicationStatus == null) return false;
            const statusInfo = this.applicationStatusOptions.find(s => s.dictValue === this.form.applicationStatus);

            // 判断是否为 PS 订单，且当前处于待审批状态（财务初审）
            const isPsOrder = (!this.form.orderNo || this.form.orderNo === 'PS订单'); // 增强 PS 订单判断逻辑
            const isFinancialApprovalForPsOrder = isPsOrder && this.form.applicationStatus === 0;

            if (this.canApprove && statusInfo) {
                // 如果是 PS 订单且是财务初审，则不显示下一审批人选择
                if (isFinancialApprovalForPsOrder) {
                    return false;
                }
                // 否则，根据 statusInfo.nextRole 决定是否显示
                return statusInfo.nextRole !== null;
            }
            return false;
        },
        receiptImageList() {
            if (this.form && this.form.receiptImages) {
                return this.form.receiptImages.split(',').filter(url => url.trim() !== '');
            }
            return [];
        }
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询提现申请列表 */
        getList() {
            this.loading = true;
            listWithdrawalApplication(this.queryParams).then(response => {
                this.withdrawalApplicationList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {};
            this.approveForm = {
                action: null,
                remark: null,
                nextApproverId: null,
                approveImageUrl: null // 新增字段，用于存储凭证图片URL
            };
            this.approveHistoryList = [];
            this.nextApproverOptions = [];
            this.canApprove = false;
            this.fileList = []; // 重置 fileList
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 文件上传处理
        handleFileUpload(param) {
            const formData = new FormData();
            formData.append("file", param.file);
            uploadFile(formData).then(response => {
                if (response.code === 200) {
                    // 成功上传后，el-upload 会自动调用 onSuccess 回调
                    param.onSuccess(response, param.file); // 告知 el-upload 成功
                } else {
                    this.$modal.msgError(response.msg || "凭证图片上传失败");
                    param.onError(new Error(response.msg || "上传失败"), param.file);
                }
            }).catch(error => {
                this.$modal.msgError("凭证图片上传失败，请稍后再试");
                param.onError(error);
            });
        },
        // 文件上传成功
        handleFileSuccess(response, file, fileList) {
            console.log('审批凭证图片上传成功 - response:', response);
            console.log('审批凭证图片上传成功 - file:', file);
            console.log('审批凭证图片上传成功 - fileList:', fileList);
            
            if (response.code === 200) {
                // 更新当前上传文件的URL
                file.url = response.data.url;
                file.name = response.fileName || file.name;
                file.status = 'success';
                
                // 更新文件列表
                this.fileList = [...fileList];
                
                // 收集所有已上传成功的图片URL，以逗号分割
                const imageUrls = [];
                this.fileList.forEach(uploadFile => {
                    if (uploadFile.url && uploadFile.status === 'success') {
                        imageUrls.push(uploadFile.url);
                    }
                });
                
                // 将多张图片URL以逗号分隔保存
                this.approveForm.approveImageUrl = imageUrls.join(',');
                console.log('审批凭证更新后的approveImageUrl:', this.approveForm.approveImageUrl);
                
                this.$modal.msgSuccess("凭证图片上传成功");
            } else {
                this.$modal.msgError(response.msg || "凭证图片上传失败");
                // 上传失败时从列表中移除该文件
                this.fileList = fileList.filter(f => f.uid !== file.uid);
            }
        },
        // 文件移除
        handleFileRemove(file, fileList) {
            console.log('审批凭证图片移除 - file:', file);
            console.log('审批凭证图片移除 - fileList:', fileList);
            
            // 更新文件列表
            this.fileList = fileList.filter(f => f.uid !== file.uid);
            
            // 重新收集所有剩余的图片URL
            const imageUrls = [];
            this.fileList.forEach(uploadFile => {
                if (uploadFile.url && uploadFile.status === 'success') {
                    imageUrls.push(uploadFile.url);
                }
            });
            
            // 更新approveImageUrl，如果没有图片则设为null
            this.approveForm.approveImageUrl = imageUrls.length > 0 ? imageUrls.join(',') : null;
            console.log('审批凭证移除后的approveImageUrl:', this.approveForm.approveImageUrl);
        },
        /** 审批按钮操作 */
        handleApprove(row) {
            this.reset();
            const id = row.id;
            this.canApprove = row.applicationStatus < 3 && row.currentApproverId === this.userId;

            getWithdrawalApplication(id).then(response => {
                this.form = response.data;
                console.log('handleApprove - form.orderNo:', this.form.orderNo);
                console.log('handleApprove - form.applicationStatus:', this.form.applicationStatus);

                if (this.form.approveHistory) {
                    try {
                        this.approveHistoryList = JSON.parse(this.form.approveHistory);
                    } catch (e) {
                        this.approveHistoryList = [];
                    }
                }

                // 判断是否为 PS 订单，且当前处于待审批状态（财务初审）
                const isPsOrder = (!this.form.orderNo || this.form.orderNo === 'PS订单'); // 增强 PS 订单判断逻辑
                const isFinancialApprovalForPsOrder = isPsOrder && this.form.applicationStatus === 0;
                console.log('handleApprove - isPsOrder:', isPsOrder, 'isFinancialApprovalForPsOrder:', isFinancialApprovalForPsOrder);

                // 只有当需要下一审批人且不是 PS 订单的特殊情况时，才获取下一审批人列表
                if (this.canApprove && this.applicationStatusOptions.find(s => s.dictValue === this.form.applicationStatus)?.nextRole && !isFinancialApprovalForPsOrder) {
                    const statusInfo = this.applicationStatusOptions.find(s => s.dictValue === this.form.applicationStatus);
                    getApprovers(statusInfo.nextRole).then(res => {
                        this.nextApproverOptions = res.data;
                    });
                } else {
                    this.nextApproverOptions = []; // 清空选项，防止显示不必要的下拉框
                }

                this.open = true;
                this.title = "提现申请审批";
            });
        },
        /** 提交审批 */
        submitApprove(action) {
            this.approveForm.action = action;

            console.log('submitApprove - approveForm before submit:', this.approveForm); // 添加这行日志

            if (action === 'REJECT') {
                if (!this.approveForm.remark) {
                    this.$modal.msgError("驳回时必须填写审批意见");
                    return;
                }
            } else if (action === 'APPROVE') {
                const isPsOrder = (!this.form.orderNo || this.form.orderNo === 'PS订单'); // 增强 PS 订单判断逻辑
                const isFinancialApprovalForPsOrder = isPsOrder && this.form.applicationStatus === 0;

                console.log('submitApprove - isPsOrder:', isPsOrder);
                console.log('submitApprove - isFinancialApprovalForPsOrder:', isFinancialApprovalForPsOrder);
                console.log('submitApprove - showNextApproverSelect:', this.showNextApproverSelect);
                console.log('submitApprove - nextApproverId before check:', this.approveForm.nextApproverId);

                if (isFinancialApprovalForPsOrder) {
                    // PS 订单在财务审批通过后，直接设置为最终状态，无需下一审批人
                    this.approveForm.nextApproverId = null; // 后端应将此解释为无需更多审批
                    console.log('submitApprove - PS order detected, nextApproverId set to null');
                } else if (this.showNextApproverSelect && !this.approveForm.nextApproverId) {
                    // 正常流程，如果显示下一审批人选择框但未选择，则报错
                    this.$modal.msgError("请选择下一位审批人");
                    return;
                }
            }

            approveApplication(this.form.id, this.approveForm).then(response => {
                this.$modal.msgSuccess("审批操作成功");
                this.open = false;
                this.getList();
            }).catch(error => {
                this.$modal.msgError(error.msg || "审批操作失败");
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('dashboard/withdrawalApplication/export', {
                ...this.queryParams
            }, `withdrawalApplication_${new Date().getTime()}.xlsx`);
        },
        /** 打款操作 */
        handlePay(row) {
            this.$modal.confirm('是否确认对申请单号为"' + row.applicationNo + '"的提现申请进行打款操作？').then(() => {
                return transferToAlipay(row.id);
            }).then(response => {
                if (response.code === 200) {
                    this.$modal.msgSuccess(response.msg);
                } else {
                    this.$modal.msgError(response.msg);
                }
                this.getList();
            }).catch(() => { });
        },
        /** 审批凭证图片预览 */
        handleApprovalPicturePreview(file) {
            if (file.url) {
                this.$preview.open(file.url, file.name || '审批凭证图片');
            } else {
                this.$message.warning('图片URL无效，无法预览。');
            }
        },
        /** 审批凭证图片超出限制 */
        handleApprovalPictureExceed(files, fileList) {
            this.$message.warning(`最多只能上传 3 张审批凭证图片！`);
        },
        /** 获取审批历史图片列表 */
        getApprovalImageList(imageUrls) {
            if (imageUrls && typeof imageUrls === 'string') {
                return imageUrls.split(',').filter(url => url.trim() !== '');
            }
            return [];
        }
    }
};
</script>

<style>
.el-timeline-item__timestamp {
    color: #606266;
    line-height: 1;
    font-size: 13px;
}

/* 收款图片容器样式 */
.receipt-images-container {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-top: 8px;
}

.receipt-image {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    border: 2px solid #e8e8e8;
    transition: all 0.3s ease;
    cursor: pointer;
}

.receipt-image:hover {
    border-color: #409eff;
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 售后收款备注样式 */
.payment-remark-container {
    background: linear-gradient(135deg, #f8fbff 0%, #f0f9ff 100%) !important;
    border: 2px solid #d1e9ff !important;
    border-radius: 12px !important;
    padding: 20px !important;
    margin-top: 12px !important;
    position: relative !important;
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15) !important;
    white-space: pre-wrap !important;
    word-wrap: break-word !important;
    line-height: 1.8 !important;
    color: #2c3e50 !important;
    font-size: 14px !important;
    font-weight: 500 !important;
    min-height: 60px !important;
    border-left: 6px solid #409eff !important;
}

.payment-remark-container::before {
    content: '' !important;
    position: absolute !important;
    left: 0 !important;
    top: 0 !important;
    bottom: 0 !important;
    width: 6px !important;
    background: linear-gradient(to bottom, #409eff, #67c23a) !important;
    border-radius: 3px 0 0 3px !important;
    z-index: 1 !important;
}

/* 审批历史图片容器样式 */
.approval-images-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
}

.approval-image {
    width: 80px;
    height: 80px;
    border-radius: 6px;
    border: 2px solid #e8e8e8;
    transition: all 0.3s ease;
    cursor: pointer;
}

.approval-image:hover {
    border-color: #409eff;
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 图片预览优化 */
::v-deep .el-image-viewer__wrapper {
    z-index: 3000;
}

::v-deep .el-image-viewer__mask {
    background-color: rgba(0, 0, 0, 0.8);
}

::v-deep .el-image-viewer__canvas {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
